package com.goverse.mancraft.man;

import android.util.Log;

import com.goverse.mancraft.CommonParams;
import com.goverse.mancraft.man.Man.IManHealthListener;
import com.goverse.mancraft.man.action.AbstractAction;
import com.goverse.mancraft.man.action.WalkAction;
import com.goverse.mancraft.world.Time;
import com.goverse.mancraft.world.WorldTimer;

import java.util.ArrayList;

/**
 * Created by gaoyu on 2017/4/15.
 */

public class ManController implements IManHealthListener, WorldTimer.OnTimePassListener{

    private boolean mShouldSleep = false;

    private ArrayList<Man> mManList = new ArrayList<>();

    public void addMan(Man man) {

        mManList.add(man);
        man.setManHealthListener(this);
        WalkAction walkAction = new WalkAction();
        walkAction.setDestination(CommonParams.MINE);
        doAction(man, walkAction);
    }

    public void destroyMan(Man man) {


    }

    public void doAction(Man man, AbstractAction action) {

        if (man.getCurrAction() != null) {
            if (man.getCurrAction().getClass() == action.getClass()) return;
            man.getCurrAction().onStop();
        }
        action.setManController(this);
        man.setCurrAction(action);
        action.setMan(man);
        action.onStart();
    }

    @Override
    public void onManLowHp(Man man, int hp) {

        Log.d("ManCraft", man.getName() + "~~~ManLowHp~~~");
        if (!man.isSleeping() && man.getMoney() != 0) {
            WalkAction walkAction = new WalkAction();
            walkAction.setDestination(CommonParams.SHOP);
            doAction(man, walkAction);
        } else if (!man.isSleeping() && man.getMoney() == 0){
            WalkAction walkAction = new WalkAction();
            walkAction.setDestination(CommonParams.MINE);
            doAction(man, walkAction);
        }
    }

    @Override
    public void onManDied(Man man) {

        Log.d("ManCraft", man.getName() + "~~~ManDied~~~");
        man.getCurrAction().onStop();
        mManList.remove(man);
    }

    public void goSleep() {

        for (int i = 0; i < mManList.size(); i++) {
            Man man = mManList.get(i);
            man.setIsSleep(true);
            man.getCurrAction().onStop();
            man.setCurrAction(null);
            WalkAction walkAction = new WalkAction();
            walkAction.setDestination(CommonParams.HOME);
            doAction(man, walkAction);
        }


    }

    public void wakeUp(Man man) {

        if (man.getHp() > man.getLowHp()) {
            WalkAction walkAction = new WalkAction();
            walkAction.setDestination(CommonParams.MINE);
            doAction(man, walkAction);
        }
    }

    @Override
    public void onTimePassed(Time time) {

        if (time.getHour() == 9 && time.getMin() == 2 && time.getSec() == 1) {
            addMan(new Man("李四"));
        }

    }
}
